import { useCurrentElement } from '@vueuse/core'
import { throttle } from 'lodash-es'
import elementResizeDetectorMaker from 'element-resize-detector'
import type { MaybeRefOrGetter } from 'vue'
import type { VChartInstance } from '@/types'
import { CHART_SYMBOL } from '@/symbol'

export function useChartAutoResize(
  chartRef: Ref<VChartInstance | undefined>,
  props: MaybeRefOrGetter<{
    autoresize?: boolean
  }>,
) {
  const el = useCurrentElement()
  const erd = elementResizeDetectorMaker()
  const resizeHandler = throttle(() => {
    chartRef.value?.resize({
      animation: {
        duration: 1000,
      },
    })
  })
  const handleAutoresize = () => {
    onMounted(() => {
      erd.listenTo(el.value, resizeHandler)
    })
  }
  const watchStopHandle = watch(
    () => toValue(props).autoresize,
    (bol?: boolean) => {
      if (!bol)
        return
      handleAutoresize()
    },
    {
      immediate: true,
    },
  )
  const resizeStatus = inject<null | Ref<boolean>>(
    CHART_SYMBOL.RESIZE_STATUS,
  )

  onBeforeUnmount(() => {
    erd.removeAllListeners(el.value)
  })

  watch(
    () => resizeStatus?.value,
    (bol: boolean | undefined | null) => {
      if (!bol)
        return
      watchStopHandle?.()
      erd.removeAllListeners(el.value)
      resizeHandler()
    },
  )
}
